package cn.kgc.novel.controller;


import cn.kgc.novel.common.ErrorCodeEnum;
import cn.kgc.novel.common.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

@Controller
public class ClientController {
    private Socket socket=null;
    @RequestMapping("/client")
    @ResponseBody
    public Result client(){
        try {
            this.socket = new Socket("127.0.0.1",9001);
            return  Result.ok();
        } catch (IOException e) {

            e.printStackTrace();
            return  Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }

    }
    @RequestMapping("/sendmsg")
    @ResponseBody
    public Result sendmsg(String msg){
        try {
            PrintStream printStream = new PrintStream(this.socket.getOutputStream());

            if(msg!=null){
                printStream.println(msg);
                printStream.flush();
                return  Result.ok();
            }else{
                return  Result.error(ErrorCodeEnum.OPERATION_FAILED);
            }


        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
